package org.dylan.web.tag.css;

import java.io.InputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dylan.core.util.ClassLoaderUtil;
import org.dylan.web.tag.css.CSSModel.CSSTheme;

/**
 * 解析定义的script脚本路径信息
 * 
 * @author dylan
 * 
 */
public class CSSDefineParser {
	private static Map<String, CSSModel> cssMap = Collections
			.synchronizedMap(new HashMap<String, CSSModel>());
	private static Log logger = LogFactory.getLog(CSSDefineParser.class);

	static {
		parseCSSDefine(ClassLoaderUtil.getResourceAsStream("css-define.xml",CSSDefineParser.class));
		parseCSSDefine(ClassLoaderUtil.getResourceAsStream("/css-define.xml",CSSDefineParser.class));
	}

	/**
	 * 从资源路径中解析脚本的定义信息
	 * 
	 * @param is
	 */
	private static void parseCSSDefine(InputStream is) {
		SAXReader saxReader = new SAXReader();
		Document document;
		try {
			document = saxReader.read(is);
		} catch (DocumentException e) {
			logger.warn("error during parse script define.", e);
			// ignored.
			return;
		}
		List list = document.selectNodes("/css-define/css");
		Iterator iter = list.iterator();
		while (iter.hasNext()) {
			Element element = (Element) iter.next();
			CSSModel model = parseCSSElement(element);
			if (model != null) {
				cssMap.put(model.getId(), model);
			}
		}
	}

	private static CSSModel parseCSSElement(Element element) {
		CSSModel model = new CSSModel();
		Element eleId = element.element("id");
		if (eleId == null) {
			logger.warn("script without 'id' element,ignored.");
			return null;
		}
		String id = eleId.getTextTrim();
		if (StringUtils.isBlank(id)) {
			logger.warn("script without 'id' defined,ignored.");
			return null;
		}
		model.setId(id);
		List<Element> pathElements = element.elements("path");
		for (Element pathElement : pathElements) {
			parsePathElement(pathElement, model);
		}
		return model;
	}

	private static void parsePathElement(Element element, CSSModel model) {
		CSSTheme theme = new CSSTheme();
		theme.setTheme(element.attributeValue("theme"));
		String path = element.getTextTrim();
		theme.setPath(path);
		model.addTheme(theme);
	}

	/**
	 * 返回解析到的script集合
	 * 
	 * @return
	 */
	public static Map<String, CSSModel> cssMap() {
		return cssMap;
	}
}
